package com.hakim.wfb.platform.controller;

import com.hakim.wfb.customer.params.trans.ConsumeRecordParameter;
import com.hakim.wfb.customer.params.user.*;
import com.hakim.wfb.customer.result.trans.ConsumeRecordView;
import com.hakim.wfb.customer.result.user.*;
import com.hkfs.fundamental.api.data.ListResultEx;
import com.hkfs.fundamental.api.data.ObjectResultEx;
import com.hkfs.fundamental.api.data.ResultEx;
import com.hkfs.fundamental.api.params.SessionIdentity;
import com.hkfs.fundamental.common.utils.ObjectUtils;
import com.hkfs.fundamental.session.SessionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hakim.wfb.customer.service.UserService;

/**
 * Created by walkman on 2017/7/1.
 */

@RestController
@RequestMapping(value = "/user", name = "用户")
public class UserController {

    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/queryRef", name = "邀请人信息", method = RequestMethod.POST)
    public ObjectResultEx<UserView> queryRef(QueryUserByRefParameter param) {
        return userService.queryUserByRef(param);
    }

    @RequestMapping(value = "/loginUser", name = "用户登录", method = RequestMethod.POST)
    public ObjectResultEx<LoginUserView> loginUser(LoginUserParameter param, HttpServletResponse response) {

        ObjectResultEx<LoginUserView> result = userService.loginUser(param);
        if (result.isFailed()) {
            return result;
        }
        LoginUserView userView = result.getDataObject();
        SessionIdentity sessionIdentity = new SessionIdentity();
        sessionIdentity.setPhone(userView.getUserPhone());
        sessionIdentity.setUuid(userView.getTid());
        sessionIdentity.setName(userView.getUserCode());
        sessionIdentity.setTerminalType(param.getTerminalType().toString());
        SessionHandler sessionHandler = new SessionHandler();
        String accessToken = sessionHandler.login(sessionIdentity, response, 2 * 60 * 60 * 1000L);
        //保存日志
        LoginUserLogParameter parameter = new LoginUserLogParameter();
        BeanUtils.copyProperties(param, parameter);
        parameter.setAccessToken(accessToken);
        userService.loginUserLog(parameter);
        LoginUserView view = new LoginUserView();
        view.setAccessToken(accessToken);
        result.setDataObject(view);
        return result.makeSuccessResult();
    }

    @RequestMapping(value = "/logoutUser", name = "用户登出", method = RequestMethod.POST)
    public ResultEx logoutUser(LogoutUserParameter param, HttpServletRequest request, HttpServletResponse response) {
        param.setAccessToken(SessionHandler.getAccessToken(request));
        SessionHandler sessionHandler = new SessionHandler();
        sessionHandler.logout(request, response);
        return userService.logoutUser(param);
    }

    @RequestMapping(value = "/islogin", name = "是否已登录", method = RequestMethod.POST)
    public ObjectResultEx<AccountLoginStatusView> isLogin(HttpServletRequest request) {
        ObjectResultEx<AccountLoginStatusView> resultEx = new ObjectResultEx<>();
        AccountLoginStatusView view = new AccountLoginStatusView();
        String accessToken = SessionHandler.getAccessToken(request);
        SessionHandler<SessionIdentity> sessionHandler = new SessionHandler<>();
        SessionIdentity sessionIdentity = sessionHandler.getSessionIdentity(accessToken, SessionIdentity.class);
        if (ObjectUtils.isEmpty(sessionIdentity)) {
            view.setStatus(0);
            resultEx.setDataObject(view);
            return resultEx.makeSuccessResult();
        }
        view.setStatus(1);
        resultEx.setDataObject(view);
        return resultEx.makeSuccessResult();
    }

    @RequestMapping(value = "/currentUser", name = "当前登录用户信息", method = RequestMethod.POST)
    public ObjectResultEx<LoginUserView> getUser(GetUserInfoParameter param, HttpServletRequest request) {
        LoginUserView view = new LoginUserView();
        SessionHandler handler = new SessionHandler();
        SessionIdentity identity = handler.getSessionIdentity(request, SessionIdentity.class);
        view.setUserName(identity.getName());
        view.setUserPhone(identity.getPhone());
        ObjectResultEx<LoginUserView> resultEx = new ObjectResultEx<>();
        resultEx.setDataObject(view);
        resultEx.makeSuccessResult();
        return resultEx;
    }


    @RequestMapping(value = "/registerUser", name = "注册用户", method = RequestMethod.POST)
    public ResultEx registerUser(RegisterUserParameter param) {

        return userService.registerUser(param);
    }

    @RequestMapping(value = "/registerAndloginUser", name = "用户注册登录", method = RequestMethod.POST)
    public ObjectResultEx<LoginUserView> registerAndloginUser(RegisterAndLoginUserParameter param, HttpServletResponse response) {
        ObjectResultEx<LoginUserView> result = new ObjectResultEx<>();
        try {
            RegisterUserParameter registParam = new RegisterUserParameter();
            BeanUtils.copyProperties(param, registParam);
            ResultEx resultEx = userService.registerUser(registParam);
            if (resultEx.isFailed()) {
                return result.makeResult(resultEx.retCode, resultEx.getRetMsg());
            }
            LoginUserView loginUserView = new LoginUserView();
//            LoginUserParameter loginParam = new LoginUserParameter();
//            loginParam.setUserCode(param.getUserCode());
//            loginParam.setPassword(param.getUserPassword());
//            loginParam.setClientIp(param.getClientIp());
//            loginParam.setTerminalType(param.getTerminalType());
//            return this.loginUser(loginParam, response);
            resultEx.setData(loginUserView);
            resultEx.setRetMsg("注册成功，请联系邀请人激活");
            return result.makeSuccessResult();
        } catch (Exception e) {
            logger.error("", e);
            return result.makeFailedResult("注册失败");
        }
    }

    /**
     * 设置交易密码
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/setTradePassword", name = "设置交易密码", method = RequestMethod.POST)
    public ResultEx setTradePassword(SetTradePasswordParameter param, HttpServletRequest request) {

        SessionHandler handler = new SessionHandler();
        SessionIdentity identity = handler.getSessionIdentity(request, SessionIdentity.class);
        param.setSessionIdentity(identity);
        param.setUserId(identity.getUuid());
        return userService.setTradePassword(param);
    }

    /**
     * 修改交易密码
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/modifyTradePassword", name = "修改支付密码", method = RequestMethod.POST)
    public ResultEx modifyTradePassword(ModifyTradePasswordParameter param, HttpServletRequest request) {
        SessionHandler handler = new SessionHandler();
        SessionIdentity identity = handler.getSessionIdentity(request, SessionIdentity.class);
        param.setSessionIdentity(identity);
        param.setUserId(identity.getUuid());
        return userService.modifyTradePassword(param);
    }

    /**
     * 找回交易密码
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/forgetTradePassword", name = "找回交易密码", method = RequestMethod.POST)
    public ResultEx forgetTradePassword(ForgetTradePasswordParameter param, HttpServletRequest request) {
        SessionHandler handler = new SessionHandler();
        SessionIdentity identity = handler.getSessionIdentity(request, SessionIdentity.class);
        param.setSessionIdentity(identity);
        param.setUserId(identity.getUuid());
        return userService.forgetTradePassword(param);
    }

    /**
     * 找回登录密码
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/forgetLoginPassword", name = "找回登录密码", method = RequestMethod.POST)
    public ResultEx forgetLoginPassword(ForgetLoginPasswordParameter param) {
        return userService.forgetLoginPassword(param);
    }

    /**
     * 修改登录密码
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/modifyLoginPassword", name = "修改登录密码", method = RequestMethod.POST)
    public ResultEx modifyLoginPassword(ModifyLoginPasswordParameter param, HttpServletRequest request) {
        SessionHandler handler = new SessionHandler();
        SessionIdentity identity = handler.getSessionIdentity(request, SessionIdentity.class);
        param.setSessionIdentity(identity);
        param.setUserId(identity.getUuid());
        return userService.modifyLoginPassword(param);
    }

    /**
     * 获取我的邀请内容
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/getInviteContent", name = "获取我的邀请内容", method = RequestMethod.POST)
    public ObjectResultEx<UserInviteContentView> getInviteContent(GetInviteContentParameter param, HttpServletRequest request) {
        SessionHandler handler = new SessionHandler();
        SessionIdentity identity = handler.getSessionIdentity(request, SessionIdentity.class);
        param.setSessionIdentity(identity);
        param.setUserId(identity.getUuid());
        return userService.getInviteContent(param);
    }

    /**
     * 绑定手机号码
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/bindMobilephone", name = "绑定手机号码", method = RequestMethod.POST)
    public ResultEx bindMobilephone(BindPhoneParameter param, HttpServletRequest request) {
        SessionHandler handler = new SessionHandler();
        SessionIdentity identity = handler.getSessionIdentity(request, SessionIdentity.class);
        param.setSessionIdentity(identity);
        param.setUserId(identity.getUuid());
        return userService.bindMobilephone(param);
    }

    /**
     * 查询用户是否已设置交易密码
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/hasTradePassword", name = "查询用户是否已设置交易密码", method = RequestMethod.POST)
    public ObjectResultEx<HasTradePasswordView> hasTradePassword(HasTradePasswordParameter param, HttpServletRequest request) {
        SessionHandler handler = new SessionHandler();
        SessionIdentity identity = handler.getSessionIdentity(request, SessionIdentity.class);
        param.setSessionIdentity(identity);
        param.setUserId(identity.getUuid());
        return userService.hasTradePassword(param);
    }

    /**
     * 查询用户是否已绑定电子钱包
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/hasBindPacket", name = "查询用户是否已绑定电子钱包", method = RequestMethod.POST)
    public ObjectResultEx<HasBindPacketView> hasBindPacket(HasBindPacketParameter param, HttpServletRequest request) {
        SessionHandler handler = new SessionHandler();
        SessionIdentity identity = handler.getSessionIdentity(request, SessionIdentity.class);
        param.setSessionIdentity(identity);
        param.setUserId(identity.getUuid());
        return userService.hasBindPacket(param);
    }

    /**
     * 查询用户是否已绑定手机号码
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/hasBindPhone", name = "查询用户是否已绑定手机号码", method = RequestMethod.POST)
    public ObjectResultEx<HasBindPhoneView> hasBindPhone(HasBindPhoneParameter param, HttpServletRequest request) {
        SessionHandler handler = new SessionHandler();
        SessionIdentity identity = handler.getSessionIdentity(request, SessionIdentity.class);
        param.setSessionIdentity(identity);
        param.setUserId(identity.getUuid());
        return userService.hasBindPhone(param);
    }

    /**
     * 登录名查询用户是否存在
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/checkUserExist", name = "登录名查询用户是否存在", method = RequestMethod.POST)
    public ObjectResultEx<HasUserExistView> checkUserExist(QueryUserParameter param) {
        ObjectResultEx<HasUserExistView> resultEx = new ObjectResultEx<>();
        HasUserExistView hasUserExistView = new HasUserExistView();
        ObjectResultEx<UserView> userViewObjectResultEx = userService.queryUserByUserCode(param);
        if (userViewObjectResultEx.isSuccess()) {
            if (userViewObjectResultEx.getDataObject() != null) {
                hasUserExistView.setHasUserExist(true);
            }
            resultEx.setDataObject(hasUserExistView);
        }
        return resultEx.makeSuccessResult();
    }


    @RequestMapping(value = "/getUserByCode", name = "用户名获取用户信息", method = RequestMethod.POST)
    public ObjectResultEx<UserView> getUserByCode(GetUserByCodeParameter param, HttpServletRequest request) {

        SessionHandler handler = new SessionHandler();
        SessionIdentity identity = handler.getSessionIdentity(request, SessionIdentity.class);
        param.setSessionIdentity(identity);

        QueryUserParameter queryUserParameter = new QueryUserParameter();
        queryUserParameter.setUserCode(param.getUserCode());
        return userService.queryUserByUserCode(queryUserParameter);

    }

    /**
     * 查询用户信息
     *
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "/user_detail", name = "查询用户信息", method = RequestMethod.POST)
    public ObjectResultEx<UserDetailView> getUserDetail(GetUserDetailParameter param, HttpServletRequest request) {

        ObjectResultEx<UserDetailView> result = new ObjectResultEx<>();
        try {

            SessionHandler handler = new SessionHandler();
            SessionIdentity identity = handler.getSessionIdentity(request, SessionIdentity.class);
            param.setSessionIdentity(identity);
            param.setUuid(identity.getUuid());
            return userService.getUserDetail(param);

        } catch (Exception e) {
            logger.error("", e);
            return result.makeFailedResult("");
        }
    }


    @RequestMapping(value = "/getAllInvest", name = "获取近期投资", method = RequestMethod.POST)
    public ListResultEx<ConsumeRecordView> getAllInvest(HttpServletRequest request) {
        ListResultEx<ConsumeRecordView> res = new ListResultEx<ConsumeRecordView>();
        try {
            SessionHandler handler = new SessionHandler();
            SessionIdentity identity = handler.getSessionIdentity(request, SessionIdentity.class);
            ConsumeRecordParameter parameter = new ConsumeRecordParameter();
            parameter.setUserId(identity.getUuid());
            return userService.getAllInvest(parameter);
        } catch (Exception e) {
            return res.makeFailedResult("查询失败");
        }
    }


    @RequestMapping(value = "/sendMsg", method = RequestMethod.POST)
    public ResultEx validMsg(String tel, HttpServletRequest request) {

//        String msg = (int) (Math.random() * Math.pow(10, 5)) + "";
        String msg = (int) ((Math.random() * 9 + 1) * 100000) + "";
        if (request != null) {
            HttpSession session = request.getSession();
            session.getId();
            session.setAttribute("tel", tel);
            session.setAttribute("msgValidCode", msg);
            session.setMaxInactiveInterval(5 * 60);
        }
        ResultEx res = userService.validMsg(tel, msg);
        return res;
    }

    @RequestMapping(value = "/validMsg", method = RequestMethod.POST)
    public ResultEx getMsg(String tel, String msg, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String code = session.getAttribute("msgValidCode").toString();
        String telphone = session.getAttribute("tel").toString();
        if (tel.equalsIgnoreCase(telphone) && msg.equalsIgnoreCase(code))
            return new ResultEx().makeSuccessResult();
        return new ResultEx().makeFailedResult("验证码错误");
    }


    @RequestMapping(value = "checkIdentity", name = "身份证校验", method = RequestMethod.POST)
    public ResultEx checkIdentity(String name, String identity, HttpServletRequest request) {
        return userService.checkIdentity(name, identity);
    }

}
